<script setup lang="ts">
import { ref, PropType, watch, unref } from 'vue'
import { propTypes } from '@/utils/propTypes'
import { ElInput } from 'element-plus'
import { Dialog } from '@/components/Dialog'
import { Icon } from '@/components/Icon'
import { Table } from '@/components/Table'
import { useTable } from '@/hooks/web/useTableTest'
import { useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { Search } from '@/components/Search'
const dialogTitle = ref('参照（请双击选择）')
const dialogVisible = ref(false)
const props = defineProps({
  getListApi: {
    type: Function as PropType<Nullable<any>>,
    default: () => null
  },
  response: {
    type: Object as PropType<Nullable<any>>,
    default: () => null
  },
  crudSchemas: {
    type: Object as PropType<Nullable<any>>,
    default: () => null
  },
  title: {
    type: String as PropType<Nullable<string>>,
    default: () => '参照（请双击选择）'
  },
  modelValue: propTypes.string.def(''),
  modelName: propTypes.string.def(''),
  nameField: propTypes.string.def(''),
  relNameField: propTypes.string.def(''),
  valueField: propTypes.string.def(''),
  relValueField: propTypes.string.def(''),
  data: {
    type: Object as PropType<Nullable<any>>,
    default: () => null
  },
  fixedSearch: {
    type: Object as PropType<Nullable<any>>,
    default: () => {}
  }
})

// console.log('props.data', props.data)

const newList = ref<any>([])
const newResponse = ref<any>({})
// 输入框的值
const valueRef = ref(props.modelValue)
const nameRef = ref(props.modelName)

const tableRef = ref<any>()

watch(
  () => props.data,
  (val: string) => {
    if (!val) return
    console.log('data', val)
  },
  {
    deep: true,
    immediate: true
  }
)

watch(
  () => props.modelValue,
  (val: string) => {
    if (val == '') {
      nameRef.value = ''
    }
    if (val === unref(valueRef)) return
    valueRef.value = val
  }
)

watch(
  () => props.modelName,
  (val: string) => {
    if (val === unref(nameRef)) return
    nameRef.value = val
  }
)

watch(
  () => props.getListApi,
  (value) => {
    if (!value) return
    newList.value = value
  },
  {
    deep: true,
    immediate: true
  }
)

watch(
  () => props.response,
  (value) => {
    if (!value) return
    newResponse.value = value
  },
  {
    deep: true,
    immediate: true
  }
)

watch(
  () => props.title,
  (value) => {
    if (!value) return
    dialogTitle.value = value
  },
  {
    deep: true,
    immediate: true
  }
)

const emit = defineEmits(['update:modelValue', 'change', 'update:modelName'])

const { register, tableObject, methods } = useTable({
  getListApi: newList.value,
  response: newResponse.value
})

watch(
  () => props.fixedSearch,
  (value) => {
    if (!value) return
    tableObject.fixedSearch = value
  },
  {
    deep: true,
    immediate: true
  }
)

const {
  //getList,
  setSearchParams
} = methods

const { allSchemas } = useCrudSchemas(props.crudSchemas)

const save = async (row) => {
  // console.log('save', row, props.valueField, row[props.valueField])
  nameRef.value = row[props.relNameField ? props.relNameField : props.nameField]
  valueRef.value = row[props.relValueField ? props.relValueField : props.valueField]
  emit('change', valueRef.value)
  emit('update:modelValue', valueRef.value)
  console.log('save', nameRef.value)
  emit('update:modelName', nameRef.value)
  dialogVisible.value = false
}
const onDialog = () => {
  setSearchParams({})
  // getList() //列表初始化的时候有调用，不用重复调用
  dialogVisible.value = true
}

// getList() //列表初始化的时候有调用，不用重复调用

const onChange = (value) => {
  // console.log('onChange', value)
  emit('update:modelName', value)
  emit('update:modelValue', '')
  // if (value == '') {
  //   emit('update:modelValue', '')
  // }
}
</script>

<template>
  <div>
    <!-- {{ valueRef }} -->
    <ElInput v-model="valueRef" type="hidden" />
    <ElInput v-model="nameRef" placeholder="点击选择" v-bind="$attrs" @change="onChange">
      <template #suffix> <Icon @click="onDialog()" icon="ep:search" /> </template>
    </ElInput>
    <Dialog v-model="dialogVisible" :title="dialogTitle" :append-to-body="true">
      <!-- {{ tableObject }} -->
      <Search
        :schema="allSchemas.searchSchema"
        @search="setSearchParams"
        @reset="setSearchParams"
      />
      <Table
        :ref="tableRef"
        v-model:pageSize="tableObject.pageSize"
        v-model:currentPage="tableObject.currentPage"
        :columns="allSchemas.tableColumns"
        :loading="tableObject.loading"
        :data="tableObject.tableList"
        :pagination="{
          total: tableObject.count
        }"
        @register="register"
        :selection="false"
        highlight-current-row
        @cell-dblclick="save"
      />
    </Dialog>
  </div>
</template>

<style lang="less"></style>
